
import os
import paho.mqtt.client as mqtt
import crcmod
import logging
import json
import glob
import uuid
import logging
import redis
import requests
import hashlib
from setting import CABINET_CURRENT_STATUS, NOW_ESP_SET, LAST_ESP_SET, CABINET_CURRENT_ORDER_STATUS

logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)


def send_mqtt_message(broker_address="47.96.3.242", broker_port=1883, topic="test/topic", message="test_message"):
    # 连接 MQTT 代理
    client = mqtt.Client()
    # client.connect("mqtt_broker_address", 1883)  # 替换为您的 MQTT 代理地址和端口

    # 建立连接
    client.connect(broker_address, broker_port)

    # 发布数据到指定主题
    client.publish(topic, message)

    # 断开 MQTT 连接
    client.disconnect()


def get_mac_address():
    "获取系统的MacAddress"

    if glob.glob("/root/.mac"):
        
        with open('/root/.mac') as f:

            mac = f.read().strip()
    else:    
        node = uuid.getnode()

        mac = uuid.UUID(int=node).hex[-12:]

    return mac

def mqtt_status_callback(status): # mqtt 回调设备新动态

        mac = get_mac_address()

        msg = {
            "mac": mac,
            "status": status,
        }

        msg = json.dumps(msg)

        send_mqtt_message(topic="rfid_cabinet/cabinet_status", message=msg)

def set_cabinet_current_status(status):
    '''设置当前柜子状态值'''
     
    r = redis.Redis(host='localhost', port=6379, db=0)

    r.set(CABINET_CURRENT_STATUS, status)

def set_cabinet_current_order_status(status):
    '''设置当前order状态值'''
     
    r = redis.Redis(host='localhost', port=6379, db=0)

    r.set(CABINET_CURRENT_ORDER_STATUS, status)

    logger.info("设置CABINET_CURRENT_ORDER_STATUS：{}".format(status))


def calculate_crc(data: bytes):
    crc = data[-2:]  # 获取最后两位字节
    crc_func = crcmod.predefined.mkPredefinedCrcFun("crc-16")
    crc_value = crc_func(data[1:-2])  # 不包含最后两位字节
    computed_crc = crc_value.to_bytes(2, byteorder='big')  # 转换为字节串（大端字节序）
    # computed_crc = crc_value.to_bytes(2, byteorder='little')  # 转换为字节串（大端字节序）

    print("computed_crc: {}".format(computed_crc))
    print("type(computed_crc): {}".format(type(computed_crc)))
    print("crc: {}".format(crc))
    print("type(crc): {}".format(type(crc)))
    return computed_crc == crc


def get_add_data_from_redis():
    '''获取当前和上次对比放入柜子中的esp标签'''
    r = redis.Redis(host='localhost', port=6379, db=0)
    
    # 获取当前和上次对比的差异（现在的esp_set中有，但上次的esp_set中没有）
    add_data = r.sdiff(NOW_ESP_SET, LAST_ESP_SET)
    
    # 将差异数据作为列表返回
    return list(add_data)

def get_delete_data_from_redis():
    '''获取当前和上次对比取出的esp标签'''
    r = redis.Redis(host='localhost', port=6379, db=0)
    
    # 获取当前和上次对比的差异（上次的esp_set中有，但现在的esp_set中没有）
    delete_data = r.sdiff(LAST_ESP_SET, NOW_ESP_SET)
    
    # 将差异数据作为列表返回
    return list(delete_data)



def upload_mp4_file(video_file_path='bh1704344438246298870.mp4'):

    if not os.path.exists(video_file_path):

        return "视频文件不存在!"
    md5 = calculate_md5(video_file_path)

    # 发送HTTP POST请求，并上传视频文件
    with open(video_file_path, 'rb') as file:
        files = {'file': file}
        response = requests.post('http://47.110.239.14:8020/shopping_video_submission', files=files, data={"md5": md5})

    # 打印响应结果
    return response.json()

def calculate_md5(filepath):
    md5 = hashlib.md5()
    
    with open(filepath, 'rb') as file:
        while True:
            data = file.read(4096) # 每次读取4KB数据
            
            if not data:
                break
                
            md5.update(data)
        
    return md5.hexdigest()
if __name__ == "__main__":

    print("mac:{}".format(get_mac_address()))

    # upload_mp4_file()
